﻿using Newtonsoft.Json;
using System;

namespace AbpProjectTemplate.Utilities.Json
{
    public class TimeSpanToStringConverter : JsonConverter
    {
        public override bool CanWrite => true;

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?);
        }


        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
                writer.WriteNull();
            else
            {
                var val = TimeSpan.Parse(value.ToString());
                writer.WriteValue(val.ToString(@"hh\:mm"));
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return null;
            if (TimeSpan.TryParse(reader.Value.ToString(), out var val))
                return val;
            throw new AppUserFriendlyException($"数据：{reader.Value}不能转换成：{objectType.Name}.");
        }
    }
}
